/**
 * 颜色调试工具
 * 用于诊断多人在线涂鸦应用中的颜色分配和同步问题
 */

export class ColorDebugger {
  constructor() {
    this.debugLog = []
    this.maxLogSize = 100
  }

  /**
   * 记录颜色相关事件
   */
  log(event, data) {
    const logEntry = {
      timestamp: new Date().toISOString(),
      event,
      data,
      playerId: data?.playerId || data?.id || 'unknown'
    }
    
    this.debugLog.push(logEntry)
    
    // 限制日志大小
    if (this.debugLog.length > this.maxLogSize) {
      this.debugLog.shift()
    }
    
    console.log(`[ColorDebugger] ${event}:`, data)
  }

  /**
   * 检查玩家颜色一致性
   */
  checkPlayerColorConsistency(players) {
    const issues = []
    
    players.forEach((player, index) => {
      const hasAvatarColor = !!player.avatarColor
      const hasBrushColor = !!player.brushColor
      const hasLegacyColor = !!player.color
      
      if (!hasAvatarColor) {
        issues.push(`玩家 ${player.nickname} (${player.id}) 缺少头像颜色`)
      }
      
      if (!hasBrushColor) {
        issues.push(`玩家 ${player.nickname} (${player.id}) 缺少画笔颜色`)
      }
      
      if (!hasLegacyColor) {
        issues.push(`玩家 ${player.nickname} (${player.id}) 缺少兼容颜色字段`)
      }
      
      // 检查颜色值是否有效
      if (hasBrushColor && !this.isValidColor(player.brushColor)) {
        issues.push(`玩家 ${player.nickname} (${player.id}) 画笔颜色无效: ${player.brushColor}`)
      }
      
      if (hasAvatarColor && !this.isValidColor(player.avatarColor)) {
        issues.push(`玩家 ${player.nickname} (${player.id}) 头像颜色无效: ${player.avatarColor}`)
      }
    })
    
    return {
      isValid: issues.length === 0,
      issues,
      playerCount: players.length
    }
  }

  /**
   * 验证颜色值是否有效
   */
  isValidColor(color) {
    if (!color || typeof color !== 'string') return false
    
    // 检查十六进制颜色格式
    const hexRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/
    if (hexRegex.test(color)) return true
    
    // 检查RGB格式
    const rgbRegex = /^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/
    if (rgbRegex.test(color)) return true
    
    // 检查RGBA格式
    const rgbaRegex = /^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*[\d.]+\s*\)$/
    if (rgbaRegex.test(color)) return true
    
    return false
  }

  /**
   * 生成颜色分配报告
   */
  generateColorReport(players, currentPlayer) {
    const report = {
      timestamp: new Date().toISOString(),
      totalPlayers: players.length,
      colorDistribution: {},
      currentPlayer: null,
      issues: []
    }
    
    // 统计颜色分布
    players.forEach(player => {
      const brushColor = player.brushColor || player.color || 'unknown'
      report.colorDistribution[brushColor] = (report.colorDistribution[brushColor] || 0) + 1
    })
    
    // 检查重复颜色
    Object.entries(report.colorDistribution).forEach(([color, count]) => {
      if (count > 1) {
        report.issues.push(`颜色 ${color} 被 ${count} 个玩家使用`)
      }
    })
    
    // 当前玩家信息
    if (currentPlayer) {
      report.currentPlayer = {
        id: currentPlayer.id,
        nickname: currentPlayer.nickname,
        avatarColor: currentPlayer.avatarColor,
        brushColor: currentPlayer.brushColor,
        legacyColor: currentPlayer.color
      }
    }
    
    return report
  }

  /**
   * 获取调试日志
   */
  getDebugLog() {
    return [...this.debugLog]
  }

  /**
   * 清空调试日志
   */
  clearDebugLog() {
    this.debugLog = []
  }

  /**
   * 导出调试报告
   */
  exportDebugReport(players, currentPlayer) {
    const report = this.generateColorReport(players, currentPlayer)
    const log = this.getDebugLog()
    
    return {
      report,
      log,
      summary: {
        totalLogEntries: log.length,
        hasIssues: report.issues.length > 0,
        issueCount: report.issues.length,
        uniqueColors: Object.keys(report.colorDistribution).length
      }
    }
  }
}

// 创建全局实例
export const colorDebugger = new ColorDebugger()

// 导出便捷方法
export const logColorEvent = (event, data) => colorDebugger.log(event, data)
export const checkColors = (players) => colorDebugger.checkPlayerColorConsistency(players)
export const getColorReport = (players, currentPlayer) => colorDebugger.generateColorReport(players, currentPlayer)
